﻿using DKPScoreWebApi.Data;
using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;

namespace DKPScoreWebApi.Services.Implementations
{
    public class WechatService : IWechatService
    {
        private readonly AppDbContext _context;
        private readonly IConfiguration _configuration;
        private readonly ILogger<WechatService> _logger;

        public WechatService(AppDbContext context, IConfiguration configuration, ILogger<WechatService> logger)
        {
            _context = context;
            _configuration = configuration;
            _logger = logger;
        }

        public async Task<WxUser> LoginAsync(LoginRequest request)
        {
            // 获取微信openid
            var openId = await GetWechatOpenIdAsync(request.Code);
            if (string.IsNullOrEmpty(openId))
                throw new ArgumentException("微信登录失败");

            // 查找或创建用户
            var user = await _context.WxUsers.FirstOrDefaultAsync(u => u.OpenId == openId);
            if (user == null)
            {
                user = new WxUser
                {
                    OpenId = openId,
                    Nickname = request.Nickname,
                    AvatarUrl = request.AvatarUrl,
                    CreatedAt = DateTime.Now
                };
                _context.WxUsers.Add(user);
                await _context.SaveChangesAsync();
            }
            else
            {
                // 更新用户信息
                user.Nickname = request.Nickname;
                user.AvatarUrl = request.AvatarUrl;
                await _context.SaveChangesAsync();
            }

            return user;
        }

        public async Task<WxUser> GetUserByOpenIdAsync(string openId)
        {
            return await _context.WxUsers.FirstOrDefaultAsync(u => u.OpenId == openId);
        }

        public async Task<WxUser> GetUserByIdAsync(int userId)
        {
            return await _context.WxUsers.FindAsync(userId);
        }

        private async Task<string> GetWechatOpenIdAsync(string code)
        {
            // 这里实现微信登录凭证校验，获取openid
            // 实际项目中需要调用微信API
            try
            {
                var appId = _configuration["Wechat:AppId"];
                var appSecret = _configuration["Wechat:AppSecret"];

                using var httpClient = new HttpClient();
                var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

                var response = await httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<WechatLoginResult>(content);

                    if (!string.IsNullOrEmpty(result.openid))
                        return result.openid;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取微信openid失败");
            }

            return null;
        }

        private class WechatLoginResult
        {
            public string openid { get; set; }
            public string session_key { get; set; }
            public string unionid { get; set; }
            public int errcode { get; set; }
            public string errmsg { get; set; }
        }
    }
}
